<!-- 管理用户 -->
<template>
  <div class="manageUser">
    <div class="search-wrap">
      <a-row
        type="flex"
        justify="space-between"
      >
        <a-col
          :span="7"
          class="display-flex align-items-center"
        >
          <span class="m-r-10 w-60">关键词</span>
          <a-input
            v-model="queryParam.search"
            placeholder="工号(账号)/姓名"
            style="width:260px"
          />
        </a-col>
        <a-col
          :span="7"
          class="display-flex align-items-center"
        >
          <span class="m-r-10 w-60">账号状态</span>
          <a-select
            :allowClear="true"
            style="width:260px"
            placeholder="请选择审核状态"
            v-model="queryParam.delFlag"
          >
            <a-select-option
              v-for="item in [{label:'正常',value:0},{label:'冻结',value:1}]"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col
          :span="7"
          class="display-flex align-items-center"
        >
          <span class="m-r-10 w-60">账号权限</span>
          <a-select
            :allowClear="true"
            style="width:260px"
            placeholder="请选择账号权限"
            v-model="queryParam.roleId"
          >
            <a-select-option
              v-for="item in roleList"
              :key="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row
        class="m-t-36 p-r-10"
        type="flex"
        justify="space-between"
      >
        <a-col :span="7">
          <a-button
            type="primary"
            @click="createManage"
          >
            添加管理员
          </a-button>
        </a-col>
        <a-col :span="7"></a-col>
        <a-col :span="7">
          <a-button
            class="m-r-30"
            type="primary"
            @click="onSearch"
          >
            检索
          </a-button>
          <a-button @click="reset">
            重置
          </a-button>
        </a-col>
      </a-row>
    </div>
    <div class="table-wrap m-t-20">
      <template>
        <s-table
          ref="sTable"
          size="default"
          :rowKey="(record) => record.id"
          :columns="columns"
          :data="loadData"
        >
          <span
            slot="action"
            slot-scope="text, record"
          >
            <a @click="edit(record)">修改</a>
            <a-divider type="vertical" />
            <a-popconfirm
              placement="top"
              ok-text="确定"
              cancel-text="取消"
              @confirm="resetPassword(record.id)"
            >
              <template slot="title">
                <span>您确定重置密码么？</span>
              </template>
              <a>重置密码</a>
            </a-popconfirm>

            <a-divider type="vertical" />
            <a
              v-if="record.delFlag == 0"
              @click="freeze(record.id)"
            >冻结</a>
            <a
              v-else
              @click="unfreeze(record.id)"
            >解冻</a>
            <a-divider type="vertical" />
            <a-popconfirm
              placement="top"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteUser(record.id)"
            >
              <template slot="title">
                <span>您确定删除该用户么？</span>
              </template>
              <a>删除</a>
            </a-popconfirm>
          </span>
        </s-table>
      </template>
    </div>
    <a-modal
      width="600px"
      :title="title"
      :visible="visible"
      @ok="handleOk"
      @cancel="visible = false"
      :destroyOnClose="true"
    >
      <div class="section">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item
            label="工号(账号)"
            prop="account"
          >
            <a-input
              :disabled="title === '编辑管理员'"
              v-model="form.account"
              placeholder="≤25位有效字符"
            />
          </a-form-model-item>
          <a-form-model-item
            label="姓名"
            prop="name"
          >
            <a-input
              v-model="form.name"
              placeholder="2~10位有效字符"
            />
          </a-form-model-item>
          <a-form-model-item
            label="手机号码"
            prop="phone"
          >
            <a-input
              v-model="form.phone"
              placeholder="请输入正确的手机号码"
            />
          </a-form-model-item>
          <a-form-model-item
            label="账号权限"
            prop="roleId"
          >
            <a-select
              v-model="form.roleId"
              placeholder="请选择账号权限"
            >
              <a-select-option
                v-for="item in roleList"
                :key="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

        </a-form-model>
      </div>
    </a-modal>
  </div>
</template>

<script>
import {
  MOBILE
} from '@/utils/reg'
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    key: 'sort',
  },
  {
    title: '工号(账号)',
    dataIndex: 'account',
    key: 'account',
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '手机号码',
    key: 'phone',
    dataIndex: 'phone',
  },
  {
    title: '账号权限',
    key: 'role',
    dataIndex: 'role',
    customRender: (text, row, index) => {
      return {
        children: text &&text.name || '--',
        attrs: {},
      };
    },
  },
  {
    title: '添加时间',
    key: 'createTime',
    dataIndex: 'createTime',
  },
  {
    title: '账号状态',
    key: 'delFlag',
    dataIndex: 'delFlag',
    customRender: (text, row, index) => {
      // 状态标识 0正常 1冻结
      let value = ''
      if (text === 0) value = '正常'
      if (text === 1) value = '冻结'
      return {
        children: value,
        attrs: {},
      };
    },
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];
let validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号码'));
  } else if (!MOBILE.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};
export default {
  name: 'manageUser',
  data () {
    return {
      title: '添加管理员',
      visible: false,
      columns,
      roleList: [],
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      managerId: '',  //管理员id
      form: {
        account: '',
        name: '',
        phone: '',
        roleId: undefined
      },
      rules: {
        account: [
          { required: true, message: '请输入工号（账号）', trigger: 'blur' },
          { min: 0, max: 25, message: '请输入≤25位有效字符', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2~10位有效字符', trigger: 'change' },
        ],
        phone: [
          { required: true, validator: validatePhone, trigger: 'change' },
        ],
        roleId: [
          { required: true, message: '请选择账号权限', trigger: 'change' },
        ],
      },
      // 查询条件参数
      queryParam: {
        delFlag: undefined,  //状态
        search: '',  //关键字
        roleId: undefined, //角色权限
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return this.$axios({
          url: '/manager/list',
          method: 'get',
          cancel: {
            _self: this
          },
          params: Object.assign(parameter, this.queryParam)
        }).then(res => {
          return {
            data: res.data.managerList,
            totalCount: res.data.total,
            pageNo: res.data.curPage
          }
        })
      },
    };
  },
  computed: {
  },
  mounted () {
    this.getRoleList()
  },
  methods: {
    onSearch () {
      this.$refs.sTable.refresh(true)
    },
    reset () {
      this.queryParam = {
        delFlag: undefined,  //状态
        search: '',  //关键字
        roleId: undefined, //角色权限
      }
    },
    createManage () {
      this.visible = true;
      this.title = '添加管理员';
      this.form = {
        account: '',
        name: '',
        phone: '',
        roleId: undefined
      }
    },
    //重置密码
    resetPassword (id) {
      this.$axios({
        url: '/manager/password/reset',
        method: 'put',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        params: {
          managerId: id
        }
      }).then(res => {
      })
    },
    //删除用户
    deleteUser (id) {
      this.$axios({
        url: '/manager',
        method: 'delete',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        params: {
          managerId: id
        }
      }).then(res => {
        this.$refs.sTable.refresh()
      })
    },
    //冻结
    freeze (id) {
      this.$axios({
        url: '/manager/freeze',
        method: 'put',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        data: {
          managerId: id
        }
      }).then(res => {
        this.$refs.sTable.refresh()
      })
    },
    //解结
    unfreeze (id) {
      this.$axios({
        url: '/manager/unfreeze',
        method: 'put',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
        data: {
          managerId: id
        }
      }).then(res => {
        this.$refs.sTable.refresh()
      })
    },
    //查询角色列表
    getRoleList (id) {
      this.$axios({
        url: '/manager/role/list',
        method: 'get',
        loadingEl: this.$el,
        cancel: {
          _self: this
        },
      }).then(res => {
        this.roleList = (res.data && res.data.roleList || []).map(v => {
          v.label = v.name
          v.value = v.id
          return v
        })
      })
    },
    //添加/编辑管理员
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let method = null
          const data = {
            account: this.form.account,
            name: this.form.name,
            phone: this.form.phone,
            roleId: this.form.roleId
          }
          if (this.title === '添加管理员') {
            method = 'post'
          } else {
            method = 'put'
            data.id = this.managerId
          }
          this.$axios({
            url: '/manager',
            method: method,
            loadingEl: this.$el,
            cancel: {
              _self: this
            },
            data: data
          }).then(res => {
            this.visible = false
            this.$message.success(this.title+'成功')
            this.$refs.ruleForm.resetFields()
            this.$refs.sTable.refresh()
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });

    },
    //打开编辑框，回显数据
    edit (record) {
      this.title = '编辑管理员'
      this.managerId = record.id
      this.visible = true
      let roleId = record.role.id
      this.form = {...record,roleId}
    }
  }
}

</script>
<style scoped lang='less'>
.manageUser {
  .search-wrap {
  }
}
</style>